<template>
    <div class="login-log-container">
        <!-- 表单搜索项 -->
        <el-form :model="params">
            <el-row :gutter="20">
                <el-col :span="5">
                    <el-form-item label="计划编号">
                        <el-input v-model="params.planNo" placeholder="请输入计划编号" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="计划名称">
                        <el-input v-model="params.planName" placeholder="请输入计划名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="计划类型">
                        <el-select v-model="params.planType" placeholder="请输入计划类型" @change="handleStatusChange">
                            <el-option label="设备点检计划" value="0" />
                            <el-option label="设备保养计划" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <el-form-item label="状态">
                        <el-select v-model="params.status" placeholder="请输入状态" @change="handleStatusChange">
                            <el-option label="草稿" value="0" />
                            <el-option label="已确认" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" plain :icon="Refresh" @click="handleReset">重置</el-button>

            </el-row>

        </el-form>
        <!-- 按钮组 -->
        <el-row class="button-group">
            <el-col :span="10">
                <div>
                    <el-button type="primary" :icon="Plus" plain @click=openInsert>新增</el-button>
                    <el-button type="success" plain :disabled="isSingleRowSelected" :icon="EditPen"
                        @click="openUpdateopenUpdate(selectedRow)">修改</el-button>


                    <el-button type="danger" plain :disabled="deleteDisabled" :icon="Delete"
                        @click="handleDelete">删除</el-button>
                    <el-button type="danger" plain :icon="Delete" @click="clearAll">清空</el-button>
                </div>
            </el-col>
            <el-col :span="14">
                <div class="button-right">
                    <el-tooltip content="隐藏搜索" placement="top">
                        <el-button :icon="Search" circle />
                    </el-tooltip>
                    <el-tooltip content="刷新" placement="top">
                        <el-button :icon="Refresh" circle />
                    </el-tooltip>
                </div>
            </el-col>
        </el-row>
        <!-- 数据表格 -->
        <el-row>
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="40" />
                <el-table-column prop="planNo" label="计划编码" align="center">
                    <template #default="scope">
                        <el-link @click="openDialog(scope.row)">
                            {{ scope.row.planNo }}
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="planName" label="计划名称" sortable align="center" />
                <el-table-column prop="planType" label="计划类型" align="center">
                    <template #default="scope">
                        {{
                            scope.row.planType === '0' ? '设备点检计划' :
                                scope.row.planType === '1' ? '设备保养计划' : '未知'
                        }}

                    </template>
                </el-table-column>
                <el-table-column prop="startTime" label="开始日期" align="center" />
                <el-table-column prop="endTime" label="结束日期" align="center" />

                <el-table-column prop="frequency" label="频率" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.frequency === '0' ? 'success' : 'danger'">
                            {{
                                scope.row.frequency === '0' ? '每日' :
                                    scope.row.frequency === '1' ? '每周' :
                                        scope.row.frequency === '2' ? '每月' :
                                            scope.row.frequency === '3' ? '每年' : '未知'
                            }} (ID: {{ scope.row.frequencyUnitId }})
                        </el-tag>
                    </template>
                </el-table-column>


                <el-table-column prop="status" label="状态" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                            {{ scope.row.status === '0' ? '草稿' : '已确认' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200px">
                    <template #default="scope">
                        <el-button :row="scope.row" type="primary" @click="openUpdate(scope.row)" text size="small"
                            :icon="EditPen">修改</el-button>
                        <el-button type="danger" text size="small" :icon="Delete" :row="scope.row"
                            @click="deleteItem(scope.row)">删除</el-button>



                    </template>
                </el-table-column>
            </el-table>
        </el-row>
        <!-- 分页组件 -->
        <el-row>
            <el-col :span="24">
                <div class="demo-pagination-block">
                    <el-pagination :current-page="params.currentPage" :page-size="params.pageSize" background
                        :default-page-size="params.pageSize" :page-sizes="pageSizes"
                        layout="total,sizes,prev,pager,next,jumper" :total="pageResult.total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>




        <el-dialog v-model="open" :title="title" width="800" @close="openDialog">
            <el-form :model="form">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="计划编码" :label-width="formLabelWidth">
                            <el-input v-model="form.planNo" autocomplete="off" />
                        </el-form-item>

                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="计划名称" :label-width="formLabelWidth">
                            <el-input v-model="form.planName" autocomplete="off" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="计划类型" :label-width="formLabelWidth">
                            <el-input v-model="form.planType" autocomplete="off" />
                        </el-form-item>

                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="频率" :label-width="formLabelWidth">
                            <div style="display: flex; align-items: center;">
                                <el-button @click="decrementFrequency">-</el-button>
                                <el-input v-model.number="form.frequency" type="number" autocomplete="off"
                                    style="width: 60px; text-align: center;" />
                                <el-button @click="incrementFrequency">+</el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="选择频率" :label-width="formLabelWidth">
                            <el-select v-model="form.frequencyUnitId" placeholder="请选择频率">
                                <el-option label="每日" value="0" />
                                <el-option label="每周" value="1" />
                                <el-option label="每月" value="2" />
                                <el-option label="每年" value="3" />
                            </el-select>
                        </el-form-item>
                    </el-col>


                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-date-picker v-model="form.startTime" type="date" placeholder="选择开始日期">

                        </el-date-picker>
                    </el-col>

                    <el-col :span="12">
                        <el-date-picker v-model="form.endTime" type="date" placeholder="选择结束日期"></el-date-picker>
                    </el-col>
                </el-row>
                <el-row :gutter="20" style="margin-top: 20px;">
                    <el-col :span="24">
                        <el-form-item label="备注" :label-width="formLabelWidth">
                            <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注"
                                style="width: 100%;"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <el-table :data="deviceLedger" style="width: 100%" @selection-change="handleSelectionChange">
                <el-table-column type="selection" :selectable="selectable" width="40" />

                <el-table-column prop="deviceNo" label="设备编码" align="center" />
                <el-table-column prop="deviceName" label="设备名称" align="center" />
                <el-table-column prop="brand" label="品牌" align="center" />
                <el-table-column prop="specificationModel" label="规格型号" align="center" />
                <el-table-column label="备注" align="center">
                    <template #default="scope">
                        <span v-if="scope.row.remark.length > 10">{{ scope.row.remark.substring(0, 10) }}...</span>
                        <span v-else>{{ scope.row.remark }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200px">
                    <template #default="scope">
                        <el-button :row="scope.row" type="primary" @click="openUpdate(scope.row)">修改</el-button>
                        <el-button type="danger" size="mini" :row="scope.row"
                            @click="deleteItem(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmAdd">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="dialogFormVisible" :title="title" width="800" @close="closeDialog">
            <el-form :model="form">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="计划编码" :label-width="formLabelWidth">
                            <el-input v-model="form.planNo" autocomplete="off" />
                        </el-form-item>

                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="计划名称" :label-width="formLabelWidth">
                            <el-input v-model="form.planName" placeholder="请输入计划名称" />
                        </el-form-item>
                       
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="计划类型" :label-width="formLabelWidth">
                            <el-input v-model="form.planType" autocomplete="off" />
                        </el-form-item>

                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="频率" :label-width="formLabelWidth">
                            <div style="display: flex; align-items: center;">
                                <el-button @click="decrementFrequency">-</el-button>
                                <el-input v-model.number="form.frequency" type="number" autocomplete="off"
                                    style="width: 60px; text-align: center;" />
                                <el-button @click="incrementFrequency">+</el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="选择频率" :label-width="formLabelWidth">
                            <el-select v-model="form.frequencyUnitId" placeholder="请选择频率">
                                <el-option label="每日" value="0" />
                                <el-option label="每周" value="1" />
                                <el-option label="每月" value="2" />
                                <el-option label="每年" value="3" />
                            </el-select>
                        </el-form-item>
                    </el-col>


                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-date-picker v-model="form.startTime" type="date" placeholder="选择开始日期">

                        </el-date-picker>
                    </el-col>

                    <el-col :span="12">
                        <el-date-picker v-model="form.endTime" type="date" placeholder="选择结束日期"></el-date-picker>
                    </el-col>
                </el-row>
                <el-row :gutter="20" style="margin-top: 20px;">
                    <el-col :span="24">
                        <el-form-item label="备注" :label-width="formLabelWidth">
                            <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注"
                                style="width: 100%;"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmAdd">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>

import { deletetpmPlan, gettpmPlanfind, inserttpmPlan, updatestpmPlan } from '@/apis/zs/index'
import { onMounted, ref, reactive} from 'vue';

import { Search, Refresh, Delete, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const dialogFormVisible = ref(false)
const title = ref('')
let planNo = ref([]) // 选中行的id数组
const tableData = ref([])   // 表格数据
const pageResult = ref({}) // 分页数据
const deleteDisabled = ref(true) // 删除按钮禁用状态,默认禁用
const open = ref(false) // 显示对话框
const deviceLedger = ref([]) // 设备台账数据
const openInsert = () => {
    dialogFormVisible.value = true
    title.value = '新增设备类型';
}
const openUpdate = (row) => {

    dialogFormVisible.value = true
    title.value = '修改设备类型';
    form.planNo = row.planNo
    form.planName = row.planName
    form.planType = row.planType
    form.startDate = row.startDate
    form.endDate = row.endDate
    form.frequency = row.frequency
    form.frequencyUnitId = row.frequencyType
    form.status = row.status
    form.remark = row.remark
    isUpdating.value = true; // 标识正在修改
}



const openDialog = (row) => {
    dialogFormVisible.value = true; // 显示对话框
    title.value = '查看计划信息'; // 设置对话框标题
    form.planNo = row.planNo; // 填写表单数据
    form.planName = row.planName;
    form.planType = row.planType;
    form.frequency = row.frequency;
    form.frequencyUnitId = row.frequencyUnitId;
    form.startTime = row.startTime; // 新增设置开始时间
    form.endTime = row.endTime;     // 新增设置结束时间
    form.remark = row.remark;
};



const incrementFrequency = () => {
    form.frequency = (form.frequency || 0) + 1; // 默认为 0，避免 NaN
};

const decrementFrequency = () => {
    if (form.frequency > 0) { // 限制最小值为 0
        form.frequency -= 1;
    }
};

//点击新增
const form = reactive({
    planNo: '',
    planName: '',
    planType: '',
    startDate: '',
    endDate: '',
    frequency: 0,
    frequencyUnitId: '',
    status: '',
    remark: ''
})


// 搜索参数
const params = ref({
    currentPage: 1,
    pageSize: 2,
    planNo: '',
    planName: '',
    planType: '',
    status: ''
})
// 分页大小
const pageSizes = [2, 5, 8, 10]

onMounted(async () => {
    // 加载登录日志列表数据
    pageResult.value = await gettpmPlanfind(params.value)
    tableData.value = pageResult.value.records
    // deviceLedger.value=await getDeviceLedgerfind(params.value)
})
/**
 * 更新状态
 * @param value 状态值
 */
const handleStatusChange = (value) => {
    params.value.status = value
}
/**
 * 处理搜索
 * @param params 搜索参数
 */
const handleSearch = async () => {
    pageResult.value = await gettpmPlanfind(params.value)
    tableData.value = pageResult.value.records
}
/**
 * 处理重置
 * @param params 搜索参数
 */
const handleReset = async () => {
    params.value = {
        currentPage: 1,
        pageSize: 2,
        planNo: '',
        planName: '',
        planType: '',
        status: ''
    }
    pageResult.value = await gettpmPlanfind(params.value)
    tableData.value = pageResult.value.records
}
/**
 * 处理分页大小变化
 * @param size 当前分页大小
 */
const handleSizeChange = async (size) => {
    params.value.pageSize = size
    pageResult.value = await gettpmPlanfind(params.value)
    tableData.value = pageResult.value.records
}
/**
 * 处理当前页码变化
 * @param currentPage 当前页码
 */
const handleCurrentChange = async (currentPage) => {
    params.value.currentPage = currentPage
    pageResult.value = await gettpmPlanfind(params.value)
    tableData.value = pageResult.value.records
}
/**
 * 自定义删除选中行的处理方法
 * @param row 行数据
 */
const selectable = (row) => {
    // 表示所有行数据都可以被选中，可以自定义选择逻辑
    return true
}
const selectedRow = ref(null); // 新增一个响应式变量来存放选中的行数据
/**
 * 处理选中行变化
 * @param val 选中行的数组
 */
const handleSelectionChange = (val) => {
    deleteDisabled.value = !val.length
    planNo.value = val.map(item => item.planNo) // 使用map方法过滤出选中行的logId数组
    selectedRow.value = val[0]; // 新增一个响应式变量来存放选中的行数据
}
/**
 * 处理删除选中行
 * @param planNo 选中行的id数组
 */
const handleDelete = () => {
    ElMessageBox.confirm(`是否确认删除访问编号为${planNo.value.join(',')}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deletetpmPlan(planNo.value)
        pageResult.value = await gettpmPlanfind(params.value)
        tableData.value = pageResult.value.records
        planNo.value = [] // 重置选中行的id数组
        ElMessage({ type: 'success', message: '删除成功' })
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' })
    })
}

const deleteItem = (row) => {
    ElMessageBox.confirm(`是否确认删除设备类型编码为${row.planNo}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 调用删除接口，传入要删除的设备类型编号
        await deletetpmPlan([row.planNo]);

        // 从表格数据中移除当前行
        tableData.value = tableData.value.filter(item => item.planNo !== row.planNo);

        // 显示成功消息
        ElMessage({ type: 'success', message: '删除成功' });
    }).catch(() => {
        // 用户取消删除
        ElMessage({ type: 'info', message: '已取消删除' });
    });

};

const clearAll = () => {
    ElMessageBox.confirm(`是否确认清空所有登录日志数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        await deletetpmPlan(planNo.value)
        pageResult.value = await gettpmPlanfind(params.value)
        tableData.value = pageResult.value.records
        planNo.value = [] // 重置选中行的id数组
        ElMessage({ type: 'success', message: '清空成功' })
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消清空' })
    })
}


// 确认新增
let confirmAdd = async () => {
    if (title.value == '新增设备类型') {
        await inserttpmPlan(form);
        ElMessage.success('新增成功');
    } else {
        await updatestpmPlan(form);
        ElMessage.success('修改成功');
    }
    dialogFormVisible.value = false;
    pageResult.value = await gettpmPlanfind(params.value)
    tableData.value = pageResult.value.records
};

// 重置表单数据
const resetForm = () => {
    form.planNo = '';
    form.planName = '';
    form.planType = '';
    form.startDate = '';
    form.endDate = '';
    form.frequency = 0;
    form.frequencyUnitId = '';
    form.status = '';
    form.remark = '';
};
const closeDialog = () => {
    resetForm();
    title.value = '';
}


</script>

<style scoped>
.dividing-line {
    text-align: center;
}

.button-right {
    text-align: right;
}

.button-group {
    margin-top: 20px;
    margin-bottom: 10px;
}

.demo-pagination-block .el-pagination {
    justify-content: end;
    margin-top: 20px;
}
</style>
